<?php
/*
 +----------------------------------------------------------------------
 + Title        : SysDict 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2019/5/21 11:17
 + Last-time    : 2019/5/21 11:17+ 86187
 + Desc         : SysDict
 +----------------------------------------------------------------------
*/


namespace app\common\service;


use think\Db;
use think\Model;

class SysDict extends Model {

	public function getInfo($table, $field, $value = null) {
		if ($table == '') {
			return self::all();
		}
		$tableFields = $this->_getTableFields($table);
		if ($field == '') {
			return $tableFields;
        }

        if ($field !== '' && is_null($value)) {
            return isset($tableFields[$field]) ? $tableFields[$field] : [];
        }

        return isset($tableFields[$field][$value]) ? $tableFields[$field][$value] : $value;

    }

    //表字段缓存
    public function _getTableFields($table, $update = false)
    {
        $key = 'tables_fields_' . $table;
        $list = cache($key);
        if ($list === false || $update) {
            $fields = db($table)->getTableFields();
            $list = [];
            foreach ($fields as $v) {
                $list[$v] = self::where('table_name', $table)
                                ->where('field_name', $v)
                                ->column('name', 'value');
            }
            cache($key, $list, 7200);
        }

        return $list;
    }

    //按照树结构组成字典JSON
    public function getTree(){
	    $data = Db::name('sys_dict')
	              ->field('table_name,field_name,name,value,remark')
	              ->whereNull('delete_time')
	              ->where('status', 'Y')
	              ->select();
	    $tables = [];
       foreach ($data as $v){
           if(!isset($tables[$v['table_name']])){
               $tables[$v['table_name']] = $v;
           }
       }
       foreach ($tables as $kk=> &$vv){
           foreach ($data as $vvv){
               if($vvv['table_name'] === $kk){
                   if(isset($vv[$vvv['field_name']]) && is_array($vv[$vvv['field_name']])){
                       $vv[$vvv['field_name']][$vvv['value']]  = $vvv;
//                       array_push($vv[$vvv['field_name']] , $vvv);
                   }else{
                       $vv[$vvv['field_name']][$vvv['value']]  = $vvv;
                   }
               }
           }
       }
        return $tables;
    }
}